package com.wjy.game.message;

/**
 * @author wjy
 * @date 2025/5/16 13:50
 * @description 请求实体
 */

import java.io.Serializable;

import cn.hutool.core.util.IdUtil;
import com.wjy.game.utils.ProtostuffUtil;

import lombok.Data;

/**
 *
 * @author wjy
 * @date 2025/5/16 13:50
 * @description 客户端请求
 */
@Data
public class Request<T extends ReqMessageData> implements Serializable {

    private String traceId;

    /**
     * 类名
     */
    private String clsName;

    /**
     * 传输数据
     */
    private byte[] data;

    private Request(String traceId, String clsName, byte[] data) {
        this.traceId = traceId;
        this.clsName = clsName;
        this.data = data;
    }

    public static <T extends ReqMessageData> Request<T> create(T data) {
        if (data != null) {
            String traceId = String.format("%s-%s-%d", data.identify(), data.operate(), IdUtil.getSnowflakeNextId());
            return new Request<>(traceId, data.getClass().getName(), ProtostuffUtil.serialize(data));
        }
        return null;
    }

    public T getObj() {
        try {
            Class<?> aClass = Class.forName(clsName);
            Object obj = ProtostuffUtil.deserialize(data, aClass);
            return (T)obj;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
